package com.zm.sgin.web;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zm.sgin.bean.Result;
import com.zm.sgin.bean.SginProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    SginProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute(properties.getSessionKey());
        if (user==null){
            String accept = request.getHeader("Accept");
            if (accept.contains("application/json")){
                //json
                ObjectMapper objectMapper = new ObjectMapper();
                Result result = new Result(0,"请先登录系统！",null);
                String json = objectMapper.writeValueAsString(result);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(json);
            }else {
                //跳转页面
                response.sendRedirect(properties.getLoginHtml());
            }
            return false;
        }
        return true;
    }
}
